﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Data.SqlClient;

namespace CommonUtil
{
    public class DBConnection
    {
        /// <summary>  
        /// 采用Socket方式，测试服务器连接  
        /// </summary>  
        /// <param name="host">服务器主机名或IP</param>  
        /// <param name="port">端口号</param>  
        /// <param name="millisecondsTimeout">等待时间：毫秒</param>  
        /// <returns></returns>  
        public static bool TestConnection(string host, int port, int millisecondsTimeout)
        {
            TcpClient client = new TcpClient();
            try
            {
                var ar = client.BeginConnect(host, port, null, null);
                ar.AsyncWaitHandle.WaitOne(millisecondsTimeout);
                return client.Connected;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                client.Close();
            }
        }

        /// <summary>  
        /// 数据库连接操作
        /// </summary>  
        /// <param name="ConnectionString">连接字符串</param>  
        /// <returns></returns>  
        public static bool TestConnection(string ConnectionString)
        {
            bool result = false;
            try
            {
                SqlConnection m_myConnection = new SqlConnection(ConnectionString);
                m_myConnection.Open();
                result = true;
                m_myConnection.Close();                
            }
            catch (Exception ex)
            {
                throw ex;                
            }
            return result;
        }

    }
}
